package com.gp.gyx.helper;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.fastjson.JSON;
import com.gp.entity.EasyExcelInfo;
import com.gp.entity.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;


import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author 黄健
 * @version 1.0.0
 * @ClassName EasyExcelHelper.java
 * @Description easyExcel工具类
 * @createTime 2022年08月25日 14:01:00
 */
@Slf4j
public class EasyExcelHelper {

    /**
     * 导出excel
     * @param response
     * @param dataList     导出的数据
     * @param classT        模板类
     * @param fileName     sheetName
     * @param sheetWriteHandlers    样式处理类
     */
    public static void writeExcelWithModel(HttpServletResponse response, List<? extends Object> dataList,
                                           Class<? extends Object> classT, String fileName, SheetWriteHandler... sheetWriteHandlers) throws IOException {

        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        fileName = URLEncoder.encode(fileName + ".xlsx", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);

        // 头的策略
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        // 单元格策略
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        // 初始化表格样式
        HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);

        ExcelWriterSheetBuilder excelWriterSheetBuilder = EasyExcel.write(response.getOutputStream(), classT).sheet(fileName).registerWriteHandler(horizontalCellStyleStrategy);
        if (null != sheetWriteHandlers && sheetWriteHandlers.length > 0) {
            for (int i = 0; i < sheetWriteHandlers.length; i++) {
                excelWriterSheetBuilder.registerWriteHandler(sheetWriteHandlers[i]);
            }
        }
        // 开始导出
        excelWriterSheetBuilder.doWrite(dataList);
    }


    public static Result<List<EasyExcelInfo>> readExcelWithModel(InputStream inputStream, List<String> importFromExcelHeader){
        List<EasyExcelInfo> list = new ArrayList<>();
        List<String> headerError = new ArrayList<>();

        EasyExcel.read(inputStream, new AnalysisEventListener<Map<Integer,String>>() {
            @Override
            public void invoke(Map<Integer,String> map, AnalysisContext analysisContext) {
                if(map != null){
                    Integer rowIndex = analysisContext.readRowHolder().getRowIndex();
                    EasyExcelInfo easyExcelInfo = new EasyExcelInfo();
                    easyExcelInfo.setRow(rowIndex);
                    List<EasyExcelInfo.CellInfo> cellInfos = new ArrayList<>();
                    for (Map.Entry<Integer, String> entry : map.entrySet()) {
                        EasyExcelInfo.CellInfo cellInfo = new EasyExcelInfo.CellInfo();
                        cellInfo.setRowIndex(entry.getKey());
                        if(entry.getValue() == null){
                            continue;
                        }
                        cellInfo.setValue(entry.getValue());
                        cellInfos.add(cellInfo);
                    }
                    easyExcelInfo.setCellInfos(cellInfos);
                    list.add(easyExcelInfo);
                }
            }

            @Override
            public void invokeHeadMap(Map<Integer,String> headMap, AnalysisContext context){
                for (int i = 0; i < importFromExcelHeader.size(); i++) {
                    String value = importFromExcelHeader.get(i);
                    if(headMap.get(i) == null || !headMap.get(i).equals(value)){
                        log.info("模板不对应 = {} ， {}",headMap.get(i),value);
                        headerError.add("请选择正确的导入模板!");
                        return;
                    }
                }
            }

            @Override
            public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                log.info(JSON.toJSONString(analysisContext));
            }
        }).sheet().doRead();

        if(CollectionUtils.isNotEmpty(headerError)){
            return new Result<>(901,"程序异常",null);
        }
        return Result.success(list);
    }
}
